const readExcel = require("./read-excel").readExcel;
const writeExcel = require("./read-excel").writeExcel;
const searchAliexpress = require("./search-fetch");
const fetchByUrl = require("./fetch");
var excelData = require("./excelData").excelData;
var goodsData = require("./excelData").goodsData;
const createMerchant = require("./api/createMerchant");
const merchantLogin = require("./api/merchantLogin");
const createStore = require("./api/createStore");
const putawayStore = require("./api/putawayStore");
const createCart = require("./api/createCart");
const balancePay = require("./api/balancePay");
const { getUserList } = require("./api/constants/user");
const setUserBalance = require("./api/setUserBalance");
const addComment = require("./api/addComment");
const deliverStore = require("./api/deliverStore");
const loginUser = require("./api/loginUser");
const perfectMerchantInfo = require("./api/perfectMerchantInfo");
const getStoreDetail = require("./api/getStoreDetail");

/**
 * 速卖通上面爬取到的商品数据
 */
var productData = require("./productData");
try {
  (async () => {
    excelData = await readExcel();
    if (excelData.goodsList.length == 0) return;
    // 创建商户
    console.log("开始创建商户");
    const merchantId = await createMerchant(excelData);
    console.log(`商户创建完成,商户ID为${merchantId}`);
    // 登录商户
    const merchantToken = await merchantLogin(merchantId);
    console.log(`商户登录成功,商户token为${merchantToken}`);

    if (excelData.companyId < 0) {
      // 完善商户信息
      await perfectMerchantInfo({
        merchantToken,
        phone: excelData.phone,
        address: excelData.address,
      });
    }

    const writeBackData = [];
    for (let i = 0; i < excelData.goodsList.length; i++) {
      goodsData = excelData.goodsList[i];
      const res = await searchAliexpress(
        goodsData.goodsKeyword,
        goodsData.goodsPrice
      );
      const detailUrl = res.detailUrl;
      writeBackData.push({
        rowIndex: goodsData.rowNumber,
        title: res.title,
        url: detailUrl,
      });
      productData = await fetchByUrl(detailUrl, global.pageHelper);
      /**
       * 创建商户
       * 价格：goodsData.goodsPrice
       * 库存：goodsData.goodsQuantity*10
       * 其他信息从productData中获取
       */
      const storeId = await createStore(
        Object.assign(productData, {
          price: goodsData.goodsPrice,
          stock: goodsData.goodsQuantity * 10,
        }),
        merchantToken
      );
      console.log(`商品创建完成,商品ID为${storeId}`);
      // 商品上架
      await putawayStore(storeId, merchantToken);
      console.log(`商品上架完成,商品ID为${storeId}`);
      // 获取用户列表
      const userList = getUserList();
      for (let i of userList) {
        console.log(`当前登录用户uid为:${i.uid}`);
        // 设置用户余额
        await setUserBalance({ userId: i.uid, addMoney: goodsData.goodsPrice });

        // 登录用户
        const userToken = await loginUser({
          account: i.account,
          password: i.password,
        });
        console.log(`用户登录成功,用户token为${userToken}`);
        // 获取商品详情
        const storeDetail = await getStoreDetail({ storeId });
        // 创建购物车
        const cartId = await createCart({
          productId: storeId,
          userToken,
          storeDetail,
        });
        console.log(`购物车创建成功,购物车ID为${cartId}`);
        // 创建支付订单并进行余额支付
        const orderId = await balancePay({
          cartId,
          uid: i.uid,
          userToken,
          addressId: i.addressId,
        });
        console.log(`订单创建成功,订单ID为${orderId}`);
        // 商品发货
        await deliverStore({ orderId, merchantToken });
        console.log(`商品发货成功,订单ID为${orderId}`);
        // 对商品进行评价
        // 注意：商品评价的ID并非商品id，而是order_product的id，这里需要加上差值
        await addComment({ orderId: parseInt(orderId) + 1, userToken });
        console.log(`商品评价成功,订单ID为${orderId}`);
      }
    }
    await writeExcel("./excel/bgd.xlsx", writeBackData);
    console.log("回写完成");
  })();
} catch (error) {
  console.log(error);
}
